package com.dadi.kotlinretrofit.adapter

import android.content.Context
import android.net.Uri
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.dadi.kotlinretrofit.R
import com.dadi.kotlinretrofit.model.Result
import com.dadi.kotlinretrofit.utils.Constants
import com.squareup.picasso.Callback
import com.squareup.picasso.Picasso
import kotlinx.android.synthetic.main.list_row.view.*

/**
 *  author: 韦敏敏
 *  date: 2020/1/5 0005
 */
class MovieAdapter(val context: Context, private val resultList:List<Result>?) : RecyclerView.Adapter<MovieAdapter.MyViewHolder>() {
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyViewHolder {
        val view = LayoutInflater.from(context).inflate(R.layout.list_row, parent, false)
        return MyViewHolder(view)
    }

    override fun getItemCount(): Int {
        return resultList?.size!!
    }

    override fun onBindViewHolder(holder: MyViewHolder, position: Int) {
        holder.bindItems(resultList?.get(position))
    }

    class MyViewHolder(itemView:View): RecyclerView.ViewHolder(itemView){
        fun bindItems(result:Result?){
            itemView.movie_title.text = result?.title
            val posterUri = Uri.parse(Constants.IMAGE_BASE_URL).buildUpon()
                .appendEncodedPath(result?.posterPath)
                .build()
            itemView.progress_bar.visibility = View.VISIBLE
            Picasso.with(itemView.context).load(posterUri.toString())
                .into(itemView.image_view_movie, object : Callback{
                    override fun onSuccess() {
                        itemView.progress_bar.visibility = View.GONE

                    }

                    override fun onError() {
                      // Show Error here

                    }

                })

        }

    }
}